package com.supor.aiot.helper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.utils.DateTimeUtils;
import com.android.baseconfig.common.utils.FileUtil;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.bumptech.glide.Glide;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.api.UserImpl;
import com.supor.aiot.common.entity.LaunchPageBean;
import com.supor.aiot.common.helper.GlobalDataCache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 描述: 启动页缓存 <br>
 * 作者: wang <br>
 * 日期: 2021/04/20 <br>
 */
public class LaunchPageHelper {
    private static final String TAG = LaunchPageHelper.class.getSimpleName();
    private Context context;
    private static final String EXTRA_PATH = FileUtil.getExternalStoragePath() + "/Download/苏泊尔/LaunchPage/";
    private LaunchPageCallback callback;

    public LaunchPageHelper(Context context) {
        this.context = context;
    }

    public Bitmap getCacheLaunchPage() {
        String launchPageStr = BaseSharedPreferences.getString(context,
                Constants.Key.LAUNCH_PAGE_INFO);
        if (TextUtils.isEmpty(launchPageStr)) {
            Logc.i("--> getCacheLaunchPage: cache pic id is empty");
            return null;
        }
        LaunchPageBean cacheInfo = GsonUtil.getInstance().toObject(launchPageStr,
                LaunchPageBean.class);
        if (!DateTimeUtils.isEffect(cacheInfo.effectTime, cacheInfo.invalidTime)) {
            return null;
        }
        String picId = cacheInfo.pictureId;
        return getCacheLaunchPage(picId);
    }

    public Bitmap getCacheLaunchPage(String picId) {
        if (TextUtils.isEmpty(picId)) {
            Logc.i("--> getCacheLaunchPage: cache pic id is empty");
            return null;
        }
        Logc.i("--> getCacheLaunchPage: cache pic id " + picId);
        String filePath =
                FileUtil.getExternalStoragePath() + "/Download/苏泊尔/LaunchPage/" + picId + ".jpg";
        File file = new File(filePath);
        if (!file.exists()) {
            Logc.i("--> getCacheLaunchPage: pic is not exist");
            return null;
        }
        return BitmapFactory.decodeFile(filePath);
    }

    /**
     * 获取启动图URL
     *
     * @param callback 回调bitmap
     */
    @SuppressLint("CheckResult")
    public void downloadLaunchPage(LaunchPageCallback callback) {
        this.callback = callback;
        Map<String, String> map = new HashMap<>();
        map.put(Constants.Key.DEVICE_ID, GlobalDataCache.getUniqueId());
        map.put(Constants.Key.IP, GlobalDataCache.OUT_IP);
        if (GlobalDataCache.userInfo != null) {
            map.put(Constants.Key.param_userId, GlobalDataCache.userInfo.getBossUserId());
        }
        if (GlobalDataCache.locationInfo != null) {
            String locationStr = GsonUtil.getInstance().toJson(GlobalDataCache.locationInfo);
            Logc.d("locationStr: " + locationStr);
            map.put(Constants.Key.LOCATION_INFO, Uri.encode(locationStr));
        } else {
            // 从缓存获取定位信息
            String locationStr = BaseSharedPreferences.getString(context,
                    Constants.Key.LOCATION_INFO);
            Logc.d("cache locationStr: " + locationStr);
            if (!TextUtils.isEmpty(locationStr)) {
                map.put(Constants.Key.LOCATION_INFO, Uri.encode(locationStr));
            }
        }
        UserImpl.getInstance().getLaunchPageUrl(map).subscribe(dataResult -> {
            if (dataResult.isSuccess()) {
                ThreadUtils.execute(() -> {
                    List<LaunchPageBean> list = dataResult.data;
                    Logc.d("--> downloadLaunchPage: list size is " + list.size());
                    if (list.size() > 0 && list.get(0) != null) {
                        LaunchPageBean bean = list.get(0);
                        cacheLaunchPage(bean);
                    } else {
                        callback.onLaunchPage(getCacheLaunchPage(), null);
                    }
                });

            } else {
                callback.onLaunchPage(getCacheLaunchPage(), null);
                Logc.d("--> downloadLaunchPage: " + dataResult.status);
            }
        }, throwable -> {
            callback.onLaunchPage(getCacheLaunchPage(), null);
            Logc.d("--> downloadLaunchPage: " + throwable);
        });
    }

    private void cacheLaunchPage(LaunchPageBean launchPageBean) {
        // 1.判断是否有更新启动图，没有有更新直接从文件decode返回bitmap或者返回null
        String cacheId = "";
        String effecTime = null;
        String invalidTime = null;
        String launchPageStr = BaseSharedPreferences.getString(context,
                Constants.Key.LAUNCH_PAGE_INFO);
        if (!TextUtils.isEmpty(launchPageStr)) {
            LaunchPageBean cacheInfo = GsonUtil.getInstance().toObject(launchPageStr,
                    LaunchPageBean.class);
            cacheId = cacheInfo.pictureId;
            effecTime = cacheInfo.effectTime;
            invalidTime = cacheInfo.invalidTime;
        }
        String id = launchPageBean.pictureId;
        String url = launchPageBean.pictureImage;
        Logc.i("cacheLaunchPage: " + "id = " + id + ", url = " + url);
        if (TextUtils.isEmpty(id) || TextUtils.isEmpty(url) || id.equals(cacheId)) {
            // 如果从手机内存获取不到文件需要重新做图片保存
            Bitmap bitmap = getCacheLaunchPage(cacheId);
            if (bitmap != null) {
                callback.onLaunchPage(DateTimeUtils.isEffect(effecTime, invalidTime) ?  bitmap: null, launchPageBean);
                return;
            }
        }
//        if (id.equals(cacheId) && isValied(data)) {
//            Logc.i("page no change, cacheId: " + cacheId);
//            Bitmap bitmap = getCacheLaunchPage(cacheId);
//            if (bitmap != null) {
//                callback.onLaunchPage(bitmap);
//                return;
//            }
//        }

        // 2.有更新，使用Glide生成bitmap返回，同时做图片缓存
        Bitmap bitmap = null;
        try {
            Logc.i("----get bitmap start");
            bitmap = Glide.with(context).asBitmap().load(url).submit().get();
            Logc.i("----get bitmap end");
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            callback.onLaunchPage(DateTimeUtils.isEffect(effecTime, invalidTime) ? getCacheLaunchPage(cacheId) : null, launchPageBean);
            return;
        }

        callback.onLaunchPage(DateTimeUtils.isEffect(launchPageBean.effectTime, launchPageBean.invalidTime) ? bitmap : null, launchPageBean);

        Bitmap finalBitmap = bitmap;
        ThreadUtils.execute(() -> {
            String filePath = EXTRA_PATH + id + ".jpg";
            FileUtil.createDirs(EXTRA_PATH);
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            try {
                boolean b = file.createNewFile();
                Logc.d("cacheLaunchPage: createNewFile: " + b);
                if (!b) {
                    Logc.d("cacheLaunchPage: createNewFile failed");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Logc.d("cacheLaunchPage: createNewFile failed: " + e.getMessage());
                return;
            }

            FileOutputStream out = null;
            try {
                out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();

            } catch (FileNotFoundException e) {
                Logc.e(TAG, "FileNotFoundException", e);
            } catch (IOException e) {
                Logc.e(TAG, "IOException", e);
            } finally {
                FileUtil.closeIoStream(out);
            }
            // 图片确定保存了才缓存ID
            BaseSharedPreferences.setString(context, Constants.Key.LAUNCH_PAGE_INFO,
                    GsonUtil.getInstance().toJson(launchPageBean));
        });

        /*DownloadImpl.getInstance().download(url, filePath, new DownloadProgressListener() {
            @Override
            public void onStart() {
                Logc.d("onStart: ");
            }

            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
            }

            @Override
            public void onFailed(Throwable throwable) {
                Logc.d("onFailed: " + throwable);
            }

            @Override
            public void onComplete(String path) {
                BaseSharedPreferences.setString(context, Constants.Key.LAUNCH_PAGE_INFO,
                        GsonUtil.getInstance().toJson(launchPageBean));
            }
        });*/
    }

    public interface LaunchPageCallback {
        void onLaunchPage(Bitmap bitmap, LaunchPageBean launchPageBean);
    }
}
